package com.bbcare.comm;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/*
 * @name:         日期格式转换类
 * @author:       DemonLee
 * @createTime:   2017.4.11
 * @description:  日期时间处理
 * @modify:
 * 
 */
public class DateUtil {
	private static final Log logger = LogFactory.getLog(DateUtil.class);

	private static final long ONE_MINUTE = 60000L;
	private static final long ONE_HOUR = 3600000L;
	private static final long ONE_DAY = 86400000L;
//	private static final long ONE_WEEK = 604800000L;

	private static final String ONE_SECOND_AGO = "秒前";
	private static final String ONE_MINUTE_AGO = "分钟前";
	private static final String ONE_HOUR_AGO = "小时前";
	private static final String ONE_DAY_AGO = "天前";
	private static final String ONE_MONTH_AGO = "月前";
	private static final String ONE_YEAR_AGO = "年前";

	public final static String FORMAT_JAVA_A = "yyyy-MM-dd HH:mm:ss";

	public final static String FROMAT_JAVA_4_DAY = "yyyyMMddHHmmss";

	public final static String FROMAT_JAVA_4_DAY2 = "yyyyMMddHHmmss";

	public final static String FROMAT_JAVA_CHAR_DAY = "yyyyMMdd";

	public final static String FROMAT_JAVA_CHAR_MONTH = "yyyyMM";
	
	public final static String FROMAT_JAVA_YEAR = "yyyy";

	public final static String FORMAT_ORACLE_A = "YYYY-MM-DD HH24:MI:SS";

	public final static String FORMAT_JAVA_B = "yyyy-MM-dd HH:mm:ss";

	public final static String FORMAT_DAY = "yyyy-MM-dd";

	public final static String FORMAT_MONTH = "yyyy-MM";

	public final static String FORMAT_LOG_A = "yyyy-MM-dd HH:mm:ss:SS";

	public final static String FORMAT_LOG_M = "yyyy-MM-dd HH:mm:ss.SSS";

	public final static String FORMAT_JAVA_Hms = "HHmmss";
	
	public final static String FORMAT_JAVA_Hm = "HHmm";

	public final static String FORMAT_Hm = "HH:mm";
    
	public final static String FORMAT_JAVA_H = "yyyy-MM-dd HH:mm";
	
	public final static String FROMAT_JAVA_DATE_MILLI= "yyyyMMddHHmmssSSS";
	
	private static ThreadLocal<DateFormat> DATE_MILLI_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FROMAT_JAVA_DATE_MILLI);
        }
    };
    
	private static ThreadLocal<DateFormat> Hm_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_JAVA_Hm);
        }
    };
    
	//private static java.text.SimpleDateFormat sf_A = new java.text.SimpleDateFormat(FORMAT_JAVA_A);
	private static ThreadLocal<DateFormat> sf_A = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_JAVA_A);
        }
    };
    
	//private static java.text.SimpleDateFormat JAVA_DAY_FORMAT = new java.text.SimpleDateFormat(FROMAT_JAVA_4_DAY);
    private static ThreadLocal<DateFormat> JAVA_DAY_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FROMAT_JAVA_4_DAY);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_DAY_CHARFORMAT = new java.text.SimpleDateFormat(FROMAT_JAVA_CHAR_DAY);
    private static ThreadLocal<DateFormat> JAVA_DAY_CHARFORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FROMAT_JAVA_CHAR_DAY);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_LOG_FORMAT = new java.text.SimpleDateFormat(FORMAT_LOG_A);
    private static ThreadLocal<DateFormat> JAVA_LOG_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_LOG_A);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_LOG_FORMAT_SSS = new java.text.SimpleDateFormat(FORMAT_LOG_M);
    private static ThreadLocal<DateFormat> JAVA_LOG_FORMAT_SSS = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_LOG_M);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_TODAY_FORMAT = new java.text.SimpleDateFormat(FORMAT_DAY);
    private static ThreadLocal<DateFormat> JAVA_TODAY_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_DAY);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_TOMONTH_FORMAT = new java.text.SimpleDateFormat(FORMAT_MONTH);
    private static ThreadLocal<DateFormat> JAVA_TOMONTH_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_MONTH);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_Hms_FORMAT = new java.text.SimpleDateFormat(FORMAT_JAVA_Hms);
    private static ThreadLocal<DateFormat> JAVA_Hm_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_Hm);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_Hms_FORMAT = new java.text.SimpleDateFormat(FORMAT_JAVA_Hms);
    private static ThreadLocal<DateFormat> JAVA_Hms_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_JAVA_Hms);
        }
    };
    
    
    private static ThreadLocal<DateFormat> JAVA_H_FORMAT = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FORMAT_JAVA_H);
        }
    };
    
    //private static java.text.SimpleDateFormat JAVA_DAY_FORMAT2 = new java.text.SimpleDateFormat(FROMAT_JAVA_4_DAY2);
    private static ThreadLocal<DateFormat> JAVA_DAY_FORMAT2 = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat(FROMAT_JAVA_4_DAY2);
        }
    };
	    
	public DateUtil() {
		// TODO Auto-generated constructor stub
	}

	public static String getLogDate(Date oldDate, int nFlag) {

		if (nFlag == 0) // 初始化
		{
			return JAVA_LOG_FORMAT.get().format(oldDate);
		} else {
			Date date = new Date();
			return JAVA_LOG_FORMAT.get().format(date) + " difftime: " + (date.getTime() - oldDate.getTime());
		}

	}

	public static String getSysDate4Hms() {
		return JAVA_Hms_FORMAT.get().format(new Date());
	}

	public static String getSysDateA() {
		Date now = new Date();
		return getDateA(now);
	}

	public static String getSysDate4Day() {
		return JAVA_DAY_FORMAT.get().format(new Date());
	}

	public static String getDateA(java.util.Date date) {
		return sf_A.get().format(date);
	}

	public static java.util.Date getDateA(String date) throws ParseException {
		return sf_A.get().parse(date);
	}

	public static java.util.Date getDate_8(String date) throws ParseException {
		return JAVA_TODAY_FORMAT.get().parse(date);
	}

	public static String getDate_8(Date date) throws ParseException {
		return JAVA_TODAY_FORMAT.get().format(date);
	}

	public static String getDateYMD(java.util.Date date) {
		return JAVA_DAY_FORMAT.get().format(date);
	}

	public static String getDateYM(java.util.Date date) {
		return JAVA_TOMONTH_FORMAT.get().format(date);
	}

	public static String getDateHm() {
		Date now = new Date();
		return JAVA_H_FORMAT.get().format(now);
	}
	
	public static String getMillSysDate() {
		Date now = new Date();
		return getMillDate(now);
	}

	
	public static String getMillDate(java.util.Date date) {
		return JAVA_LOG_FORMAT_SSS.get().format(date);
	}

	// 获取当天时间hh:ss
	public static String getMh() {
		Date now = new Date();
		return JAVA_Hm_FORMAT.get().format(now);
	}
	
	// 获取当天时间hhss
	public static String getHm() {
		Date now = new Date();
		return Hm_FORMAT.get().format(now);
	}
	
	// 获取当天时间yyyyMMdd
		public static String getCurrDate() {
			Date now = new Date();
			return JAVA_DAY_CHARFORMAT.get().format(now);
		}
	
	// 获取当天时间yyyy-MM-dd
	public static String getCurrDate2() {
		Date now = new Date();
		return JAVA_TODAY_FORMAT.get().format(now);
	}

	// 获取当天时间yyyy-MM-dd
	public static Date getDate(String str) {
		Date date = null;
		try {
			date = JAVA_TODAY_FORMAT.get().parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	// 获取昨天（某天）时间yyyyMMdd
	public static String getCurrDateByDay(int day, String calcType) {
		Date now = null;
		if (Constants.PLUS_CHAR.equals(calcType)) {
			now = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * day);
		} else if (Constants.SUBTRACT_CHAR.equals(calcType)) {
			now = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * day);
		}
		return JAVA_DAY_CHARFORMAT.get().format(now);
	}

	// 获取昨天（某天）时间yyyy-MM-dd
	public static String getCurrDateByDay2(int day, String calcType) {
		Date now = null;
		if (Constants.PLUS_CHAR.equals(calcType)) {
			now = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * day);
		} else if (Constants.SUBTRACT_CHAR.equals(calcType)) {
			now = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * day);
		}
		return JAVA_TODAY_FORMAT.get().format(now);
	}

	/**
	 * 获取月份起始日期
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getMinMonthDate(String date) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(JAVA_DAY_FORMAT.get().parse(date));
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		return JAVA_DAY_FORMAT.get().format(calendar.getTime());
	}

	/**
	 * 获取月份起始日期 按14位日期
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getMinMonthDateForChar(String date) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(JAVA_DAY_FORMAT.get().parse(date));
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		return JAVA_DAY_CHARFORMAT.get().format(calendar.getTime()) + "000000";
	}

	/**
	 * 获取月份最后日期
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getMaxMonthDate(String date) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(JAVA_DAY_FORMAT.get().parse(date));
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		return JAVA_DAY_FORMAT.get().format(calendar.getTime());
	}

	/**
	 * 获取月份最后日期 按14位日期
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getMaxMonthDateForChar(String date) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(JAVA_DAY_FORMAT.get().parse(date));
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		return JAVA_DAY_CHARFORMAT.get().format(calendar.getTime()) + "235959";
	}

	/**
	 * 时间计算:
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getFirstDateMinus(String date, int plusNum) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(JAVA_DAY_FORMAT.get().parse(date));
		calendar.add(Calendar.MONTH, -plusNum);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		return JAVA_DAY_CHARFORMAT.get().format(calendar.getTime()) + "000000";
	}

	/**
	 * @param timeStr
	 *            2010-01-25 21:51:30
	 * @return 20100125215130
	 */
	public static String getTimeString(String timeStr) {
		String str = timeStr.replaceAll("-", "").replace(":", "").replace(" ", "");
		return str;
	}

	/**
     * @param timeStr
     *            2010-01-25 21:51:30 2010/01/25 21:51:30
     * @return 20100125215130
     */
    public static String getTimeString2(String timeStr) {
        String str = timeStr.replaceAll("-", "").replace("/", "").replace(":", "").replace(" ", "");
        return str;
    }

	public static String getFullStr(int n) {
		return n < 10 ? "0" + n : n + "";
	}

	/**
	 * 针对mysql的timeStamp返回的结果进行处理
	 * 
	 * @param 2010-01-25
	 *            21:51:30.0
	 * @return 2010-01-25 21:51:30
	 */
	public static String getTimeStampSec(String timeStr) {
		String str = timeStr;
		if (21 == timeStr.length()) {
			str = timeStr.substring(0, timeStr.length() - 2);
		}
		return str;
	}

	/**
	 * 针对mysql的timeStamp返回的结果进行处理
	 * 
	 * @param 2010-01-25
	 *            21:51:30.0
	 * @return 2010-01-25
	 */
	public static String getTimeStampDay(String timeStr) {
		String str = timeStr;
		if (10 <= timeStr.length()) {
			str = timeStr.substring(0, 10);
		}
		return str;
	}

	/**
	 * 日期加减计算
	 * 
	 * @param date
	 *            +/- num
	 * @return date yyyyMMdd
	 * @throws ParseException
	 */
	public static String calcDay(String timeStr, String calcType, int num) {
		String str = timeStr.replaceAll("-", "").replace("/", "").replace(" ", "");
		Date timeDate = null;
		try {
			timeDate = JAVA_DAY_CHARFORMAT.get().parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			logger.error("timeStr==" + timeStr + ", str==" + str);
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DATE_PARSE_ERROR, "时间解析错误，格式不正确！"));
		}
		long numtime = (long) num * 24 * 60 * 60 * 1000;
		if (Constants.PLUS_CHAR.equals(calcType)) {
			str = JAVA_DAY_CHARFORMAT.get().format(new Date(timeDate.getTime() + numtime));
		} else if (Constants.SUBTRACT_CHAR.equals(calcType)) {
			str = JAVA_DAY_CHARFORMAT.get().format(new Date(timeDate.getTime() - numtime));
		}
		return str;
	}

	/**
	 * 日期加减计算
	 * 
	 * @param date
	 *            +/- num
	 * @return date yyyy-MM-dd
	 * @throws ParseException
	 */
	public static String calcDay2(String timeStr, String calcType, int num) {
	    if(0 == num) {
	        return timeStr;
	    }
		Date timeDate = null;
		String str = timeStr;
		try {
			timeDate = JAVA_TODAY_FORMAT.get().parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
		}
		long numtime = (long) num * 24 * 60 * 60 * 1000;
		if ("+".equals(calcType)) {
			str = JAVA_TODAY_FORMAT.get().format(new Date(timeDate.getTime() + numtime));
		} else if ("-".equals(calcType)) {
			str = JAVA_TODAY_FORMAT.get().format(new Date(timeDate.getTime() - numtime));
		}
		return str;
	}

	/**
	 * 日期加减小时
	 * 
	 * @param date
	 *            +/- hour
	 * @return date yyyyMMddHHmmss
	 * @throws ParseException
	 */
	public static String calcDayByHour(String timeStr, String calcType, float num) {
		String str = timeStr.replaceAll("-", "").replace("/", "").replace(":", "").replace(" ", "");
		Date timeDate = null;
		try {
			timeDate = JAVA_DAY_FORMAT2.get().parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			logger.error("timeStr==" + timeStr + ", str==" + str);
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DATE_PARSE_ERROR, "时间解析错误，格式不正确！"));
		}
		float numtime = (float) 60 * 60 * 1000 * num;
		long lltime = (long) numtime;
		if (Constants.PLUS_CHAR.equals(calcType)) {
			str = JAVA_DAY_FORMAT2.get().format(new Date(timeDate.getTime() + lltime));
		} else if (Constants.SUBTRACT_CHAR.equals(calcType)) {
			str = JAVA_DAY_FORMAT2.get().format(new Date(timeDate.getTime() - lltime));
		}
		return str;
	}
	
	/**
	 * 日期加减分钟
	 * 
	 * @param date
	 *            +/- minute
	 * @return date yyyy-MM-dd HH:mm:ss
	 * @throws ParseException
	 */
	public static String calcDayByMinute(String timeStr, String calcType, float num) {
		String str = timeStr.replaceAll("-", "").replace("/", "").replace(":", "").replace(" ", "");
		Date timeDate = null;
		try {
			timeDate = JAVA_DAY_FORMAT2.get().parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			logger.error("timeStr==" + timeStr + ", str==" + str);
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DATE_PARSE_ERROR, "时间解析错误，格式不正确！"));
		}
		float numtime = (float) 60 * 1000 * num;
		long lltime = (long) numtime;
		if (Constants.PLUS_CHAR.equals(calcType)) {
			str = sf_A.get().format(new Date(timeDate.getTime() + lltime));
		} else if (Constants.SUBTRACT_CHAR.equals(calcType)) {
			str = sf_A.get().format(new Date(timeDate.getTime() - lltime));
		}
		return str;
	}

	/**
	 * 根据传入的时间 计算距离当前 多少秒、分、时 等
	 * 
	 * @param timeStr
	 * @return
	 */
	public static String formatTimedifference(String timeStr) {
		Date date = Timestamp.valueOf(timeStr);// 转换时间字符串为Timestamp搜索
		long delta = new Date().getTime() - date.getTime();
		if (delta < 1L * ONE_MINUTE) {
			long seconds = toSeconds(delta);
			return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;
		}
		if (delta < 60L * ONE_MINUTE) {
			long minutes = toMinutes(delta);
			return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;
		}
		if (delta < 24L * ONE_HOUR) {
			long hours = toHours(delta);
			return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;
		}
		/*
		 * if (delta < 48L * ONE_HOUR) { return "昨天"; }
		 */
		if (delta < 30L * ONE_DAY) {
			long days = toDays(delta);
			return (days <= 0 ? 1 : days) + ONE_DAY_AGO;
		}

		if (delta < 365 * ONE_DAY) {
			long months = toMonths(delta);
			return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;
		} else {
			long years = toYears(delta);
			return (years <= 0 ? 1 : years) + ONE_YEAR_AGO;
		}
	}

	private static long toSeconds(long date) {
		return date / 1000L;
	}

	private static long toMinutes(long date) {
		return toSeconds(date) / 60L;
	}

	private static long toHours(long date) {
		return toMinutes(date) / 60L;
	}

	private static long toDays(long date) {
		return toHours(date) / 24L;
	}

	private static long toMonths(long date) {
		return toDays(date) / 30L;
	}

	private static long toYears(long date) {
		return toDays(date) / 365L;
	}

	/**
	 * 获取最近6个月，经常用于统计图表的X轴
	 */
	public static String[] getLast6Months() {
		String[] last6Months = new String[6];
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); // 要先+1,才能把本月的算进去</span>
		for (int i = 0; i < 6; i++) {
			cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); // 逐次往前推1个月
			last6Months[5 - i] = JAVA_TOMONTH_FORMAT.get().format(cal.getTime());
		}

		return last6Months;
	}

	/**
	 * 获取最近7天日期
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static String[] getLast7days() throws ParseException {
		String[] str = new String[7];
		for (int i = 0; i < 7; i++) {
			Calendar c = Calendar.getInstance();
			c.add(Calendar.DATE, -i);
			Date monday = c.getTime();
			String preMonday = JAVA_TODAY_FORMAT.get().format(monday);
			str[6 - i] = preMonday;
		}

		return str;
	}

	/**
	 * 获取当前周的第一天和最后一天
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static String[] getWeekStartEnd() throws ParseException {
		String[] str = new String[2];
		Calendar cal = Calendar.getInstance();

		cal.setTime(new Date());
		int d = 0;
		if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
			d = -6;
		} else {
			d = 2 - cal.get(Calendar.DAY_OF_WEEK);
		}
		cal.add(Calendar.DAY_OF_WEEK, d);
		// 所在周开始日期
		str[0] = JAVA_TODAY_FORMAT.get().format(cal.getTime());
		cal.add(Calendar.DAY_OF_WEEK, 6);
		// 所在周结束日期
		str[1] = JAVA_TODAY_FORMAT.get().format(cal.getTime());
		return str;
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public static Date addDay(Date oldDate, int day) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(oldDate);
		calendar.add(Calendar.DATE, day);// 把日期往后增加天.整数往后推,负数往前移动
		return calendar.getTime(); // 这个时间就是日期往后推一天的结果
	}
	
	public static Date subDay(Date oldDate, int day) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(oldDate);
		calendar.add(Calendar.DATE,-day);// 把日期往后增加天.整数往后推,负数往前移动
		return calendar.getTime(); // 这个时间就是日期往后推一天的结果
	}
	
	
	/**
	 * 日期比较大小
	 * @throws ParseException
	 */
	public static int compare_date (String DATE1, String DATE2) {
		 Date dt1 = null;
         Date dt2 = null;
		try {
			dt1 = JAVA_TODAY_FORMAT.get().parse(DATE1);
			dt2 = JAVA_TODAY_FORMAT.get().parse(DATE2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
		}
		//前一个时间比后时间大
		if (dt1.getTime() > dt2.getTime()) {
            return 1;
        } else if (dt1.getTime() < dt2.getTime()) {
        //前一个时间比后时间小
            return -1;
        } else {
        //时间相等
            return 0;
        }
	}
	
   public static boolean isValidDate(String str,String format) {  
        //String str = "2007-01-02";
	    SimpleDateFormat sdf = new SimpleDateFormat(format);
        try{  
        	sdf.parse(str);  
            return true;  
        }catch(Exception e){  
            return false;  
        }  
    }  
   
   /**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetweenStr(String smdate, String bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date smdate1 = sdf.parse(smdate);
		Date bdate1 = sdf.parse(bdate);
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate1);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

    /**
     * 计算两个日期之间相差的天数（可能返回负数）
     * 
     * @param yyyyMMdd
     * @return 相差天数
     * @throws ParseException
     */
    public static Integer daysBetweenDateStr(String dateStr1, String dateStr2) throws ParseException {
        if (StringUtils.isBlank(dateStr1) || StringUtils.isBlank(dateStr2)) {
            return null;
        }
        // 格式化日期
        String smdate = dateStr1.replaceAll("-", "").replace("/", "").replace(" ", "");;
        String bdate = dateStr2.replaceAll("-", "").replace("/", "").replace(" ", "");;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date smdate1 = sdf.parse(smdate);
        Date bdate1 = sdf.parse(bdate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate1);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

	 /**
		 * 计算两个日期之间相差的月份
		 * 
		 * @param minDate
		 *            较小的时间
		 * @param maxDate
		 *            较大的时间
		 * @return 月份
		 * @throws ParseException
		 */
	public static List<String> daysBetweenmouth (String minDate, String maxDate) throws ParseException {
		ArrayList<String> result = new ArrayList<String>();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
	
	    Calendar min = Calendar.getInstance();
	    Calendar max = Calendar.getInstance();
	
	    min.setTime(sdf.parse(minDate));
	    min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
	
	    max.setTime(sdf.parse(maxDate));
	    max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
	
	    Calendar curr = min;
	    while (curr.before(max)) {
	     result.add(sdf.format(curr.getTime()));
	     curr.add(Calendar.MONTH, 1);
	    }
	    return result;
	}
	
	/**
	 * 获取当前日期的前或者后的日期
	 * 
	 * @param flag
	 * @return 如果flag= -1 表示前一天，flag = 1表示后一天 ，flag= 0表示的是当天
	 */
	public static String getYesterday(int flag) {
		String str = "";
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		// calendar.setTime(df.parse(date));
		calendar.add(Calendar.DATE, flag);
		str = df.format(calendar.getTime());
		return str;
	}
	
	 /** 
     * 两个时间相差距离多少天多少小时多少分多少秒 
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00 
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00 
     * @return String 返回值为：xx天xx小时xx分xx秒 
	 * @throws ParseException 
     */  
    public static int getDistanceTime(String str1, String str2) throws ParseException {  
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
        Date one;  
        Date two;  
        long day = 0;  
        long hour = 0;  
        long min = 0;  
        long sec = 0;  
            one = df.parse(str1);  
            two = df.parse(str2);  
            long time1 = one.getTime();  
            long time2 = two.getTime();  
            long diff ;  
            if(time1<time2) {  
                diff = time2 - time1;  
            } else {  
                diff = time1 - time2;  
            }  
            day = diff / (24 * 60 * 60 * 1000);  
            hour = (diff / (60 * 60 * 1000) - day * 24);  
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); 
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);  
            min=hour*60+min;
            sec=sec+1;
        return  (int) day;
    }  
    
	
	public static Date subMonth(Date oldDate, int month) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(oldDate);
		calendar.add(Calendar.MONTH,-month);// 把日期往后增加天.整数往后推,负数往前移动
		return calendar.getTime(); // 这个时间就是日期往前/后推N天的结果
	}
	
	public static Date addMonth(Date oldDate, int month) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(oldDate);
		calendar.add(Calendar.MONTH,month);// 把日期往后增加天.整数往后推,负数往前移动
		return calendar.getTime(); // 这个时间就是日期往前/后推N天的结果
	}
	
	public static String getSysDateMilliStr() {
		return DATE_MILLI_FORMAT.get().format(new Date());
	}
	
	public static void main(String args[]) throws ParseException {
		System.out.println(calcDayByMinute(DateUtil.getSysDateA(),Constants.SUBTRACT_CHAR,10));
	}
}
